package com.daye.homework.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.*;
import java.io.IOException;
import java.net.http.HttpResponse;

@WebFilter(filterName = "UserFilter" , urlPatterns = "/*")
public class UserFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        // System.out.println(request.getServletPath());

        if ("/login".equals(request.getServletPath())){
            //登录 , 直接放行
            chain.doFilter(req, resp);
        }

        String username = null;
        String password = null;

        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0){
            for (Cookie cookie : cookies) {
                if ("username".equals(cookie.getName())){
                    username = cookie.getValue();
                }

                if ("password".equals(cookie.getName())){
                    password = cookie.getValue();
                }
            }

        }

        if ("admin".equals(username)  && "123456".equals(password)){
            //用户已登录 , 且帐号密码正确
            if ("index.jsp".equals(request.getServletPath())){
                //如果这小子去登录页 , 就给他强行带到管理页
                request.getRequestDispatcher("managerPage.jsp").forward(request,resp);
            }
            chain.doFilter(request,response);
        }else {
            //返回登录页
            request.getRequestDispatcher("index.jsp").forward(request,resp);
        }
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
